<script setup lang="ts">

import Navigator from "../components/NavigatorRoot.vue";
import HeaderTitle from "../components/HeaderTitle.vue";
import {ref, reactive, onMounted} from "vue";
import router from "../Router";
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
import {currentTaskForm, TaskForm} from "../store/taskStore.ts";
import {getUserById, getUserByRole} from "../network/userApi.ts";
import {getCode, getTaskById, getType, updateTask} from "../network/taskApi.ts";
import {currentRoleIndex, navigatorDict} from "../utils/UserUtils.ts";




const formSize = ref<ComponentSize>('default')
const taskFormRef = ref<FormInstance>()
const taskForm = reactive<TaskForm>({
})
const rules = reactive<FormRules<TaskForm>>({
  title: [
    { required: true, message: '请输入项目名称', trigger: 'change' },
    { min: 3, max: 50, message: '名称应该在3~50字内', trigger: 'change' },
  ],
  description: [
    {
      required: true,
      message: '请详细描述该项目',
      trigger: 'change',
    },
  ],
  submitUser: [
    {
      required: true,
      message: '请选择任务提交人，负责任务的调查',
      trigger: 'change',
    },
  ],
  checkUser: [
    {
      required: true,
      message: '请选择任务审核人，负责调查结果的审核',
      trigger: 'change',
    },
  ],
  start: [
    {
      type: 'date',
      required: true,
      message: '请选择任务开始时间',
      trigger: 'change',
    },
  ],
  end: [
    {
      type: 'date',
      required: true,
      message: '请选择任务结束时间',
      trigger: 'change',
    },
  ],
  types: [
    {
      required: true,
      message: '请选择调查类型',
      trigger: 'change',
    },
  ],
})
let taskId = {id: Number(localStorage.getItem("modifyTaskId"))}
onMounted(()=>{
  getTaskById(taskId).then(res=>{
    console.log('（0：找得到）getTaskById-res.data.code:',res.data.code)
    if(res.data.code == 0){
      for (let taskFormKey in res.data.data) {
        taskForm[taskFormKey] = res.data.data[taskFormKey]
      }
      let submitUserTemp = {"id": res.data.data.submitUserId}
      getUserById(submitUserTemp).then(res => {
        taskForm.submitUser = res.data.data.nickname
      })
      let checkUserTemp = {"id": res.data.data.checkUserId}
      getUserById(checkUserTemp).then(res => {
        taskForm.checkUser = res.data.data.nickname
      })
      let temStart = JSON.stringify(res.data.data.startTime)
      let temEnd = JSON.stringify(res.data.data.endTime)
      taskForm.startTime = temStart.substring(1,11)+' '+ temStart.substring(12,20)+'.000'
      taskForm.endTime = temEnd.substring(1,11)+' '+ temEnd.substring(12,20)+'.000'
      taskForm.start = temStart.substring(1,11)+'T'+ temStart.substring(12,20)+'.000Z'
      taskForm.end = temEnd.substring(1,11)+'T'+ temEnd.substring(12,20)+'.000Z'

    }else{

    }
    console.log(taskForm)
  })
})


const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log("执行任务的修改")
      updateTask(taskForm).then(res=>{
        console.log(res.data.message)
        alert("任务基本信息修改成功")
        router.push("/modifyTaskMap")
      })
    } else {
      console.log('检验失败')
    }
  })
}

let submitUserOptions = ref([])
let checkUserOptions =ref([])
let typesOptions =ref([])

let checkRoleBody = ref({
  "limit": 0,
  "offset": 0,
  "role": "审核人"
})
getUserByRole(checkRoleBody.value).then(res=>{
  let users = res.data.data.records
  let arr =[]
  users.forEach(user=>{
    let u_dict = { //对应select框的键值对
      label:user.nickname,
      value:user.nickname
    }
    arr.push(u_dict)
  })
  checkUserOptions.value = arr
  // console.log(checkUserOptions.value)
})

let submitRoleBody = ref({
  "limit": 0,
  "offset": 0,
  "role": "实施人"
})
getUserByRole(submitRoleBody.value).then(res=>{
  let users = res.data.data.records
  let arr =[]
  users.forEach(user=>{
    let u_dict = { //对应select框的键值对
      label:user.nickname,
      value:user.nickname
    }
    arr.push(u_dict)
  })
  submitUserOptions.value = arr
  // console.log(submitUserOptions.value)
})

let typeBody = ref({
  dict_key: '任务类型',
})
getType(typeBody.value).then(res=>{
  let tlist = res.data.data
  let arr =[]
  tlist.forEach(type=>{
    let t_dict = { //对应select框的键值对
      label:type,
      value:type
    }
    arr.push(t_dict)
  })
  typesOptions.value = arr
  // console.log(typesOptions.value)
})

function handleTypesChange(data){
  console.log(data)
}


console.log("localStorage.getItem(\"currentRoleIndex\"):",localStorage.getItem("currentRoleIndex"))
currentRoleIndex.value = localStorage.getItem("currentRoleIndex") ? localStorage.getItem("currentRoleIndex") : 5
</script>

<template>
  <div class="flex flex-col h-full w-full fixed top-0 right-0  bg-gray-2 gap-2">
    <header-title></header-title>
    <div class="flex grow gap-2">
      <component :is="navigatorDict[currentRoleIndex]" class="w-38"></component>
      <div class="ml-40 bg-white grow h-full flex flex-col">
        <div class="flex justify-start items-center gap-3 h-12 ml-5">
          <div class="border-#84b9bf rounded-full border-1 border-solid w-5 h-5"></div>
          <div class="flex justify-center items-center text-5 text-bold">修改项目基本信息</div>
        </div>
        <div class="flex flex-col justify-center items-center mt-15">
          <el-form
              ref="taskFormRef"
              style="max-width: 600px; max-height: 100%"
              :model="taskForm"
              :rules="rules"
              label-width="auto"
              class="demo-ruleForm"
              :size="formSize"
              status-icon

          >
            <el-form-item label="任务标题" prop="title" style="margin-bottom: 30px">
              <el-input v-model="taskForm.title" />
            </el-form-item>
            <el-form-item label="任务提交人" prop="submitUser"  style="margin-bottom: 30px">
              <el-select
                  v-model="taskForm.submitUser"
                  placeholder="请选择任务提交人，负责调查的实施"
                  style="width:400px"
              >
                <el-option
                    v-for="item in submitUserOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="任务审核人" prop="checkUser" style="margin-bottom: 30px">
              <el-select
                  v-model="taskForm.checkUser"
                  placeholder="请选择任务审核人，负责调查结果的审核"
                  style="width: 400px"
              >
                <el-option
                    v-for="item in checkUserOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="开始时间" required  style="margin-bottom: 30px">
              <el-date-picker
                  v-model="taskForm.start"
                  type="datetime"
                  placeholder="Select date and time"
              />
            </el-form-item>
            <el-form-item label="结束时间" required  style="margin-bottom: 30px">
              <el-date-picker
                  v-model="taskForm.end"
                  type="datetime"
                  placeholder="Select date and time"
              />
            </el-form-item>
            <el-form-item label="调查类型" prop="types"  style="margin-bottom: 30px">
              <el-select
                  v-model="taskForm.types"
                  placeholder="请选择调查类型"
                  style="width: 400px"
              >
                <el-option
                    v-for="item in typesOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="任务描述" prop="description"  style="margin-bottom: 30px">
              <el-input v-model="taskForm.description" type="textarea" />
            </el-form-item>
          </el-form>
          <div>
            <el-button type="primary" color="#C7E8E1FF"
                       :dark="true" @click="submitForm(taskFormRef)">
              下一步
            </el-button>
          </div>

        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
input[type=radio]{
  width: 16px;
  height: 16px;
  margin-top: 2px;
  position: relative;
}
input[type=radio]::after {
  position: absolute;
  top: 0;
  color: #000;
  width: 16px;
  height: 16px;
  display: inline-block;
  visibility: visible;
  padding-left: 0px;
  text-align: center;
  content: ' ';
  border-radius: 100%;
}
input[type=radio]:checked::after {
  content: "✓";
  color: #fff;
  font-size: 10px;
  line-height: 15px;
  background-color: #42BEAD;
}




</style>